<template>
  <GlobalDrawer
    v-model="visible"
    :title="title"
    size="80%"
    :before-close="handleClose"
    @confirm="handleConfirm"
  >
    <div class="drawer-content drawer-content-wrapper">
      <ContactForm
        ref="contactFormRef"
        :customer-id="customerId"
        :contact-id="contactId"
        :mode="mode"
        :contact-data="contactData"
        @success="handleSuccess"
        @cancel="handleCancel"
      />
    </div>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, computed, watch, defineEmits, defineProps } from 'vue'
  import ContactForm from './ContactForm.vue'
  import { GlobalDrawer } from '@/components/common'
  import type { CustomerContact } from '@/types/customer'

  // 定义props和emits
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    customerId: {
      type: [Number, String],
      required: true,
    },
    contactId: {
      type: [Number, String],
      default: '',
    },
    mode: {
      type: String,
      default: 'add', // add或edit
    },
    contactData: {
      type: Object as () => CustomerContact | null,
      default: null,
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  // 表单引用
  const contactFormRef = ref<any>(null)

  // 抽屉可见性
  const visible = computed({
    get: () => props.modelValue,
    set: val => emit('update:modelValue', val),
  })

  // 抽屉标题
  const title = computed(() => {
    return props.mode === 'add' ? '新增联系人' : '编辑联系人'
  })

  // 确认按钮点击
  const handleConfirm = async () => {
    if (contactFormRef.value) {
      await contactFormRef.value.handleSubmit()
    }
  }

  // 关闭抽屉
  const handleClose = () => {
    visible.value = false
    return true
  }

  // 表单提交成功
  const handleSuccess = () => {
    visible.value = false
    emit('success')
  }

  // 取消操作
  const handleCancel = () => {
    visible.value = false
  }

  // 监听mode变化
  watch(
    () => props.mode,
    newVal => {
      console.log('联系人操作模式变化:', newVal)

      // 如果是新增模式，重置表单
      if (newVal === 'add' && contactFormRef.value) {
        contactFormRef.value.resetForm()
      }
    }
  )

  // 监听customerId变化
  watch(
    () => props.customerId,
    newVal => {
      console.log('客户ID变化:', newVal)
    }
  )

  // 监听抽屉可见性变化
  watch(visible, newVal => {
    console.log('抽屉可见性变化:', newVal)

    // 如果抽屉打开且是新增模式，重置表单
    if (newVal && props.mode === 'add' && contactFormRef.value) {
      contactFormRef.value.resetForm()
    }
  })
</script>

<style scoped>
  .drawer-content {
    height: 100%;
    overflow-y: auto;
  }
</style>
